package com;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class SocketServer extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ServerSocket server;
	private Socket socket;

	private JButton startBtn;
	private JButton stopBtn;
	private JTextArea textArea;
	private JLabel countLabel;

	private boolean started = false;
	private int count = 0;

	void initUI() {

		setSize(600, 800);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		startBtn = new JButton("启动服务");
		stopBtn = new JButton("停止服务");
		textArea = new JTextArea();
		countLabel = new JLabel();

		JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

		topPanel.add(startBtn);
		topPanel.add(stopBtn);
		topPanel.add(countLabel);
		add(topPanel, BorderLayout.NORTH);
		add(textArea, BorderLayout.CENTER);

		setVisible(true);

		startBtn.addActionListener(e -> {
			if (!started) {

				new Thread(() -> {
					startServer();
				}).start();
			} else {
				JOptionPane.showMessageDialog(this, "服务已启动");
			}
		});

		stopBtn.addActionListener(e -> {
			if (started) {

				try {
					server.close();
					started = false;
				} catch (IOException e1) {
					print("停止服务失败");
				}

			} else {
				JOptionPane.showMessageDialog(this, "服务未启动,无法停止");
			}
		});
	}

	void startServer() {
		try {
			server = new ServerSocket(8848);
			started = true;
			print("服务器套接字创建成功等待连接");
			while (!server.isClosed()) {
				socket = server.accept();
				new HandlerThread(socket);
				addCount();
			}
		} catch (BindException e) {
			print("启动失败" + e.toString());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		started = false;
		countLabel.setText("连接总数0");
		print("socket服务已停止");
	}

	void addCount() {
		count++;
		countLabel.setText("连接总数" + count);
	}

	void removeCount() {
		count--;
		countLabel.setText("连接总数" + count);
	}

	void print(String msg) {
		textArea.append(msg + "\n");
	}

	private class HandlerThread implements Runnable {
		private Socket socket;
		private String key;

		private InputStreamReader reader = null;
//		char chars[] = new char[64];
//		int len;
		private String temp = null;

		public HandlerThread(Socket client) {
			socket = client;
			new Thread(this).start();
		}

		public void run() {
			key = socket.getInetAddress().toString().substring(1) + "|" + socket.getPort() + " ";
			print(key + "已连接");
			try {
				InputStreamReader isr = new InputStreamReader(socket.getInputStream());// 接收客户端的数据
				BufferedReader br = new BufferedReader(isr);// 存入缓存
				;
				while ((temp = br.readLine()) != null) {
					print(key + ":" + temp);
				}
//				reader = new InputStreamReader(socket.getInputStream());
//				while ((len = reader.read(chars)) != -1) {
//					temp = new String(chars, 0, len);
//					for(int i=0;i<len;i++) {
//						System.out.print((int)chars[i]+",");
//					}
//					System.out.println();
//					System.out.println(key+len+" :"+temp);
//				}
				if (socket.getKeepAlive() == false) {
					reader.close();
					System.out.println("客户端" + key + "-->退出");
					socket.close();
				}
			} catch (Exception e) {

			}
			removeCount();
			print(key + "断开连接");
		}
	}

	public static void main(String[] args) {
		SocketServer server = new SocketServer();
		server.initUI();
	}
}
